﻿using SoldiHive.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace SoldiHive.Core.Persistence
{
	public class CompaniesRepository : ICompanyRepository
	{
		private ICompanyRepositoryConfiguration configuration;

		private IList<Company> companies;

		public CompaniesRepository(ICompanyRepositoryConfiguration configuration)
		{
			this.configuration = configuration;
		}

		public Company GetCompany(string ticker)
		{
			var company = this.GetCompanies()
				.Where(cmpn => cmpn.Ticker.Equals(ticker, StringComparison.InvariantCultureIgnoreCase))
				.SingleOrDefault();

			return company;
		}

		public IList<Company> GetCompanies()
		{
			var companies = this.companies.Select(company => company).ToList();

			return companies;
		}

		public IList<Company> GetCompanies(Sector sector)
		{
			var companies = this.companies.Where(p => p.Sector == sector).ToList();

			return companies;
		}

		public IList<Company> GetCompanies(Industry industry)
		{
			var companies = this.companies.Where(p => p.Industry == industry).ToList();

			return companies;
		}

		public IList<Company> GetCompanies(SubIndustry subIndustry)
		{
			var companies = this.companies.Where(p => p.SubIndustry == subIndustry).ToList();

			return companies;
		}

		public void LoadCompanies()
		{
			var companiesFile = this.configuration.CompaniesFile;
			using (var file = File.OpenRead(companiesFile))
			using (var reader = new StreamReader(file))
			{
				this.LoadCompanies(reader);
			}
		}

		public void LoadCompanies(TextReader reader)
		{
			if (this.companies != null)
			{
				this.companies.Clear(); 
			}
			else
			{
				this.companies = new List<Company>();
			}

			string line;
			while (!string.IsNullOrEmpty((line = reader.ReadLine())))
			{
				var values = line.Split(new string[] { "\",\"" }, 6, StringSplitOptions.None)
					.Select(s => s.Trim())
					.Select(s => s.Trim("\"".ToCharArray()))
					.ToArray();

				var ticker = values[0];
				var name = values[1];
				var cap = double.Parse(values[2]);
				var sector = new Sector(values[3]);
				var industry = new Industry(values[4]);
				var subIndustry = new SubIndustry(values[5]);

				var company = new Company(ticker, name, cap, sector, industry, subIndustry);;

				if (!this.companies.Any(cmpn => cmpn == company))
				{
					this.companies.Add(company);
				}
			}
		}
	}
}